package payment.mobilepos.unionpay.com.zing;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.Result;
import com.sdk.LogUtils;

import java.io.IOException;
import java.lang.reflect.Field;

import payment.mobilepos.unionpay.com.R;
import payment.mobilepos.unionpay.com.demo.base.UPMPosBaseActivity;
import payment.mobilepos.unionpay.com.zing.camera.CameraManager;
import payment.mobilepos.unionpay.com.zing.decode.DecodeThread;
import payment.mobilepos.unionpay.com.zing.utils.BeepManager;
import payment.mobilepos.unionpay.com.zing.utils.CaptureActivityHandler;
import payment.mobilepos.unionpay.com.zing.utils.InactivityTimer;

public class CaptureActivity extends UPMPosBaseActivity implements SurfaceHolder.Callback {

    private SurfaceView mScanPreview;

    private RelativeLayout mScanContainerView;
    private LinearLayout mScanCropView;
    private ImageView mScanLineView;
    private TextView mStatusView;

    private CameraManager mCameraManager;
    private CaptureActivityHandler mCaptureActivityHandler;
    private InactivityTimer mInactivityTimer;
    private BeepManager mBeepManager;

    private Rect mCropRect = null;

    private boolean mIsHasSurface = false;

    public Handler getHandler() {
        return mCaptureActivityHandler;
    }

    public CameraManager getCameraManager() {
        return mCameraManager;
    }

    public Rect getCropRect() {
        return mCropRect;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_capture);

        initView();
        initData();
    }

    private void initView() {
        findViewById(R.id.nav_btn_left).setOnClickListener(this);
        findViewById(R.id.nav_btn_right).setVisibility(View.GONE);
        findViewById(R.id.btn_return).setOnClickListener(this);

        mScanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        mStatusView = (TextView) findViewById(R.id.status_view);
        mScanContainerView = (RelativeLayout) findViewById(R.id.capture_container);
        mScanCropView = (LinearLayout) findViewById(R.id.capture_crop_view);
        mScanLineView = (ImageView) findViewById(R.id.capture_scan_line);

        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation
                .RELATIVE_TO_PARENT, 0.9f);
        animation.setDuration(4500);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        mScanLineView.startAnimation(animation);
    }

    private void initData() {
        mIsHasSurface = false;
        mInactivityTimer = new InactivityTimer(this);
        mBeepManager = new BeepManager(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_return:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // CameraManager must be initialized here, not in onCreate(). This is necessary because
        // we don't
        // want to open the camera driver and measure the screen size if we're going to show the
        // help on
        // first launch. That led to bugs where the scanning rectangle was the wrong size and
        // partially
        // off screen.

        initCapture();
    }

    private void initCapture() {
        mCameraManager = new CameraManager(getApplication());

        mCaptureActivityHandler = null;

        mInactivityTimer.onResume();

        if (mIsHasSurface) {
            // The activity was paused but not stopped, so the surface still
            // exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(mScanPreview.getHolder());
        } else {
            // Install the callback and wait for surfaceCreated() to init the
            // camera.
            mScanPreview.getHolder().addCallback(this);
        }
    }

    @Override
    protected void onPause() {
        if (mCaptureActivityHandler != null) {
            mCaptureActivityHandler.quitSynchronously();
            mCaptureActivityHandler = null;
        }
        mInactivityTimer.onPause();
        mBeepManager.close();
        mCameraManager.closeDriver();
        if (!mIsHasSurface) {
            mScanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mInactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            LogUtils.e("surfaceCreated() gave us a null surface!");
        }
        if (!mIsHasSurface) {
            mIsHasSurface = true;
            initCamera(surfaceHolder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mIsHasSurface = false;
    }


    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    public void handleDecode(Result rawResult, Bundle bundle) {
        mInactivityTimer.onActivity();
        mBeepManager.playBeepSoundAndVibrate();

//        bundle.putInt("width", mCropRect.width());
//        bundle.putInt("height", mCropRect.height());
        bundle.putString("result", rawResult.getText());

        LogUtils.e("capture result text:" + rawResult.getText());
//        ActivityUtils.showCaptureResultActivity(this, rawResult.getText());
        finish();
    }


    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (mCameraManager.isOpen()) {
            LogUtils.w("initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            mCameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a RuntimeException.
            if (mCaptureActivityHandler == null) {
                mCaptureActivityHandler = new CaptureActivityHandler(this, mCameraManager,
                        DecodeThread.ALL_MODE);
            }
            initCrop();
        } catch (IOException ioe) {
            LogUtils.w(ioe.toString());
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            LogUtils.w("Unexpected error initializing camera/"+ e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        // camera error
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("相机打开出错，请稍后重试");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }

        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.show();
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = mCameraManager.getCameraResolution().y;
        int cameraHeight = mCameraManager.getCameraResolution().x;

        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        mScanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();

        int cropWidth = mScanCropView.getWidth();
        int cropHeight = mScanCropView.getHeight();

        /** 获取布局容器的宽高 */
        int containerWidth = mScanContainerView.getWidth();
        int containerHeight = mScanContainerView.getHeight();

        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;

        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;

        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
